#!/usr/bin/env python 
# -*- coding:utf-8 -*-

import datetime
import time

from pymongo import MongoClient
from utils.log import log

class dao(object):
    # mongo
    __mongo_cof = {"host": "localhost", "port": 27017}
    __mongo_client = MongoClient(host=__mongo_cof["host"], port=__mongo_cof["port"])
    __test01 = __mongo_client['test01']
    __regionInfo_coll = __test01['regionInfo']
    __roomInfo_coll = __test01['roomInfo']
    __version = "20181202"
    __log = log.getLog('zr')

    # 根据zoom查询地区信息
    def find_list_byzoom(self, zoom, sort=None, skip=None, limit=None):
        cursor = self.__regionInfo_coll.find({'zoom': zoom})
        # sort
        sort_params = []
        while sort is not None and len(sort) > 0:
            sort_params.insert(0, sort.popitem())
        if len(sort_params) > 0:
            cursor = cursor.sort(sort_params)
        # skip & limit
        if skip is not None and type(skip) == int:
            cursor = cursor.skip(int(skip))
        if limit is not None and type(limit) == int:
            cursor = cursor.limit(int(limit))
        return cursor

    # 保存地区信息
    def update_region(self, entity):
        code = entity['code']
        zoom = entity['zoom']
        if code & zoom:
            # 保存额外信息
            entity['updTime'] = int(time.time())  # 秒级时间戳
            entity['updTimeStr'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            query = {'code': code, 'zoom': zoom}
            update = {'$set': entity, '$addToSet': {'vers_prices': "{}_{}".format(self.__version, entity['sellPrice'])}}
            self.__regionInfo_coll.update_one(query, update, upsert=True)
        else:
            self.__log.error("dao.update_region update失败，参数异常：code={}, zoom={}".format(code, zoom))

    # 保存房屋信息 TODO
    def update_room(self, entity):
        rid = entity['id']
        if rid:
            # 保存额外信息
            entity['updTime'] = int(time.time())  # 秒级时间戳
            entity['updTimeStr'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            query = {'rid': rid}
            update = {'$set': entity, '$addToSet': {'vers_prices': "{}_{}".format(self.__version, entity['sell_price'])}}
            self.__roomInfo_coll.update_one(query, update, upsert=True)
        else:
            self.__log.error("dao.update_room update失败，参数异常：rid={}".format(rid))
